import { useRequest } from "ahooks";
import { FC, useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { useNavigate, useParams } from "react-router";
import { find_one } from "../../../server/manageServer";
import {
  changePageIsPublished,
  changePageTitle,
} from "../../../store/pageInfoReducer";
import useGetPageInfo from "../../../hooks/useGetPageInfo";
import { Button, Result } from "antd";
import StatHeader from "./components/StatHeader";
import { changeSelectedList } from "../../../store/componentsReducer";
import ComponentList from "./components/ComponentList";
import PageStat from "./components/PageStat";
import ChartStat from "./components/ChartStat";

const Stat: FC = () => {
  const { _id } = useParams();

  const dispatch = useDispatch();
  // 状态提升 selectedId type
  const [selectedComponentId, setSelectedComponentId] = useState("");
  const [selectedComponentType, setSelectedComponentType] = useState("");
  useEffect(() => {
    if (!_id) return;
    run(_id);
  }, []);
  const { run } = useRequest(find_one, {
    manual: true,
    onSuccess(result) {
      const { data } = result.data;
      if (!data) return;

      dispatch(changePageTitle(data.title));
      dispatch(changePageIsPublished(data.isPublished));
      dispatch(changeSelectedList(data.componentList));
    },
    onFinally() {},
  });

  const nav = useNavigate();
  const { isPublished } = useGetPageInfo();
  const genContentElem = () => {
    if (typeof isPublished === "boolean" && !isPublished) {
      return (
        <div className="flex-1">
          <Result
            status="warning"
            title="该页面尚未发布"
            extra={
              <Button type="primary" onClick={() => nav(-1)}>
                返回
              </Button>
            }
          ></Result>
        </div>
      );
    }
    return (
      <>
        <div className="w-90">
          左侧
          <ComponentList
            selectedComponentId={selectedComponentId}
            setSelectedComponentId={setSelectedComponentId}
            setSelectedComponentType={setSelectedComponentType}
          />
        </div>
        <div className="flex-auto bg-#fff py-3 px-4.5">
          <PageStat
            selectedComponentId={selectedComponentId}
            setSelectedComponentId={setSelectedComponentId}
            setSelectedComponentType={setSelectedComponentType}
          />
        </div>
        <div className="w-100 bg-#fff py-3 px-4.5 ml-6 overflow-hidden">
          <ChartStat
            selectedComponentId={selectedComponentId}
            selectedComponentType={selectedComponentType}
          />
          {selectedComponentType}
        </div>
      </>
    );
  };

  return (
    <div className="flex flex-col bg-#f0f2f5 min-h-100vh">
      <div>
        <StatHeader />
      </div>
      <div className="flex-auto py-3">
        <div className="flex mx-6">{genContentElem()}</div>
      </div>
    </div>
  );
};
export default Stat;
